//
//  NSData+NSData_AES128.m
//  LotteryAPI
//
//  Created by CharlieLiao on 2017/3/16.
//  Copyright © 2017年 Enjoy. All rights reserved.
//

#import "ToHexExtension.h"

@implementation NSString (ToHexConvertExtension)

- (NSData*)hexStringToData
{
    NSString *urlRegex = @"[a-fA-F0-9]*";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegex];
    BOOL flag = [predicate evaluateWithObject:self];
    if (flag)
    {
        NSAssert(0 == self.length % 2, @"Hex strings should have an even number of digits (%@)", self);
        
        NSUInteger dataLength = self.length/2;
        
        unsigned char cacheBytes[dataLength];
        unsigned char *bp = cacheBytes;
        
        char buf[3];
        buf[2] = '\0';
        for (CFIndex i = 0; i < self.length; i++) {
            
            buf[0] = [self characterAtIndex:i++];
            buf[1] = [self characterAtIndex:i];
            
            char *b2 = NULL;
            *bp++ = strtol(buf, &b2, 16);
            NSAssert(b2 == buf + 2, @"String should be all hex digits: %@ (bad digit around %ld)", self, i);
        }
        
        return [NSData dataWithBytes:cacheBytes length:dataLength];
    }
    else
        return nil;
}

@end

@implementation NSData (ToHexConvertExtension)

- (NSString *)toHexString {
    /* Returns hexadecimal string of NSData. Empty string if data is empty.   */
    
    const unsigned char *dataBuffer = (const unsigned char *)[self bytes];
    
    if (dataBuffer == NULL || self.length == 0) return @"";
    
    NSUInteger dataLength  = [self length];
    NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
    
    for (int i = 0; i < dataLength; ++i)
        [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long)dataBuffer[i]]];
    
    return [NSString stringWithString:hexString];
}

@end
